﻿<%@ WebHandler Language="C#" Class="DealFaultBillHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using External.APICalling;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;

public class DealFaultBillHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    private uLMSMfgOrderIBusiness dal = uMESBusinessFactory.instance.GetuLMSMfgOrderObject();
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetProductSelect":
                    GetProductSelect(context);
                    break;
                case "initData":
                    initData(context);
                    break;
                case "GenerateContainer":
                    GenerateContainer(context);
                    break;    
                case "GetDealMfgorder":
                    GetDealMfgorder(context);
                    break;
                case "GetDealContainer":
                    GetDealContainer(context);
                    break;
                case "SaveDealMfgOrder":
                    SaveDealMfgOrder(context);//保存排故订单信息
                    break;
                case"SaveDealContainer":
                    SaveDealContainer(context);
                    break;   
                case "SaveDealMfgOrderStatus":
                    SaveDealMfgOrderStatus(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    void initData(HttpContext context) 
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable employeedt = m_CommonObj.GetEmplyeeListByRole("工艺员", m_UserInfo.FactoryID);
        result.DBTable = employeedt;
        result.ReturnData = m_UserInfo;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void GetProductSelect(HttpContext context)
    {
        string productName = context.Request["Name"].ToString();
        var sql = @"SELECT p.PRODUCTID ID,pb.PRODUCTNAME||':'||p.PRODUCTREVISION NAME,p.DESCRIPTION,pb.REVOFRCDID,pb.PRODUCTNAME,p.PRODUCTREVISION 
                FROM PRODUCT p 
                LEFT JOIN PRODUCTBASE pb ON pb.PRODUCTBASEID =p.PRODUCTBASEID 
                WHERE pb.PRODUCTNAME  LIKE '%{0}%' ";
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "查询完成" };
        DataTable dtProduct = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, productName));
        if (dtProduct.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "未查询到件号";
        }
        else
        {
            foreach (DataRow item in dtProduct.Rows)
            {
                if (item["ID"].ToString() == item["REVOFRCDID"].ToString())
                {
                    item["NAME"] += "(默认)";
                }
            }
            dtProduct.AcceptChanges();
            result.DBTable = dtProduct;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void GenerateContainer(HttpContext context) {
        uMESProcessResult result = new uMESProcessResult();
        var requestPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var containerName=requestPara["productinfo"].Split(':')[0]+"/"+requestPara["dealFualtBill"];
        var mfgorderid=requestPara["mfgorderid"];
        if (requestPara.ContainsKey("mfgordername")&&!string.IsNullOrWhiteSpace(requestPara["mfgordername"])) {
            var sql3 = @"select * from mfgorder m LEFT JOIN ORDERTYPE o2 ON o2.ORDERTYPEID =m.ORDERTYPEID where m.mfgordername='{0}' and o2.ORDERTYPENAME ='排故订单'";
            DataTable mdt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql3, requestPara["mfgordername"]));
            if (mdt.Rows.Count == 0)
            {
                result.Message = "查询不到对应的排故订单号";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            else { 
                mfgorderid=mdt.Rows[0]["mfgorderid"].ToString();
            }
        }
        var sql = @"SELECT c.CONTAINERNAME FROM CONTAINER c WHERE c.CONTAINERNAME LIKE '{0}%'";
        //if (!string.IsNullOrWhiteSpace(mfgorderid)) { sql += " and c.MFGORDERID ='" + mfgorderid + "'"; }
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, containerName));
        var sql2 = @"SELECT * FROM DEALFAULTBILL d WHERE d.DEALFAULTBILLNAME ='{0}' AND d.isuse=0";
        DataTable dt2 = DatabaseHelper.Query_ReturnDatTable(string.Format(sql2, requestPara["dealFualtBill"]));
        if (dt2.Rows.Count == 0) { result.Message = "查询不到对应的排故单号"; }
        else
        {
            result.Result = true;
            result.ReturnData = containerName + "-" + (dt.Rows.Count < 10 ? "0" + (dt.Rows.Count + 1) : (dt.Rows.Count + 1).ToString());
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void GetDealMfgorder(HttpContext context)
    {
        var requestPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var sql = @"SELECT m.MFGORDERID,m.MFGORDERNAME,m.PRODUCTFAMILYNAME,m.QTY,m.PLANNEDSTARTDATE,m.PLANNEDCOMPLETIONDATE,cs.LASTCHANGEDATE CREATEDATE
                ,pb.PRODUCTNAME||':'||p.PRODUCTREVISION PRODUCTNAME,p.DESCRIPTION,DECODE(o.ORDERSTATUSNAME,'打开','启用','停用') ORDERSTATUS,u.ATTRIBUTEVALUE ENGINENO,
                (SELECT count(1) FROM CONTAINER cci WHERE cci.MFGORDERID=m.MFGORDERID) CONTAINERCOUNT,
                (SELECT sum(qty) FROM CONTAINER cci WHERE cci.MFGORDERID=m.MFGORDERID) CONTAINERQTY,o2.ORDERTYPENAME 
                FROM MFGORDER m 
                LEFT JOIN PRODUCT p ON p.PRODUCTID =m.PRODUCTID 
                LEFT JOIN PRODUCTBASE pb ON pb.PRODUCTBASEID =p.PRODUCTBASEID 
                LEFT JOIN ORDERSTATUS o ON o.ORDERSTATUSID =m.ORDERSTATUSID 
                LEFT JOIN CHANGESTATUS cs ON cs.PARENTID =m.MFGORDERID 
                LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
                LEFT JOIN ORDERTYPE o2 ON o2.ORDERTYPEID =m.ORDERTYPEID 
                where 1=1 AND o2.ORDERTYPENAME ='排故订单' ";
        sql += " and m.FACTORYID ='" + m_UserInfo.FactoryID + "'";
        if (requestPara.ContainsKey("ProductName") && !string.IsNullOrWhiteSpace(requestPara["ProductName"]))
        {
            sql += @" and pb.PRODUCTNAME like '%" + requestPara["ProductName"] + "%'";
        }
        if (requestPara.ContainsKey("ProductFamily") && !string.IsNullOrWhiteSpace(requestPara["ProductFamily"]))
        {
            sql += @" and m.PRODUCTFAMILYNAME like '%" + requestPara["ProductFamily"] + "%'";
        }
        if (requestPara.ContainsKey("MfgOrdername") && !string.IsNullOrWhiteSpace(requestPara["MfgOrdername"]))
        {
            sql += @" and m.MFGORDERNAME like '%" + requestPara["MfgOrdername"] + "%'";
        }
        if (requestPara.ContainsKey("OrderStatus") && !string.IsNullOrWhiteSpace(requestPara["OrderStatus"]))
        {
            sql += @" and o.ORDERSTATUSNAME='" + (requestPara["OrderStatus"].Equals("1") ? "关闭" : "打开") + "'";
        }
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = sql;
        var result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void GetDealContainer(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var mfgorderids = context.Request["mfgorderids"].ToString();
        var sql = @" SELECT u.ATTRIBUTEVALUE DEALFAULTBILL,pb.PRODUCTNAME,c.CONTAINERNAME,decode(c.CONTAINERTYPE,2,'批量加工',3,'批量带子序号',7,'单件加工','其他')CONTAINERTYPE
                ,decode(cci.CONTAINERSTATUS,1,'在制',2,'入库','其他')  CONTAINERSTATUS,c.QTY 
                FROM Container c
                LEFT JOIN PRODUCT p  ON p.PRODUCTID =c.PRODUCTID 
                LEFT JOIN PRODUCTBASE pb ON pb.PRODUCTBASEID =p.PRODUCTBASEID 
                LEFT JOIN CONTAINERCURRENTINFO cci ON cci.CONTAINERID =c.CONTAINERID 
                LEFT JOIN USERATTRIBUTE u ON u.PARENTID =c.CONTAINERID AND u.USERATTRIBUTENAME ='排故单号'
                WHERE c.MFGORDERID IN ('{0}') order by c.CONTAINERNAME ";
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, mfgorderids.Replace(",", "','")));
        result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "" : "查询不到数据";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }



    void SaveDealMfgOrder(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        if (m_UserInfo == null)
        {
            result.Result = false;
            result.Message = "登录过期，请重新登录";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        var requestPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var para = new Dictionary<string, string>();
        para.Add("Qty", requestPara["qty"]);
        para.Add("PlannedStartDate", Convert.ToDateTime(requestPara["startDate"]).ToString("yyyy-MM-ddTHH:mm:ss"));
        para.Add("PlannedCompletionDate", Convert.ToDateTime(requestPara["endDate"]).ToString("yyyy-MM-ddTHH:mm:ss"));
        para.Add("ProductName", requestPara["productName"]);
        para.Add("ProductRevision", requestPara["productVer"]);
        para.Add("Name", requestPara["mfgOrderName"]);
        para.Add("productFamily", requestPara["productFamily"]);
        para.Add("engineNo", requestPara["engineNo"]);
        para.Add("OrderStatus", "打开");
        para.Add("UserName", m_UserInfo.APIUserName.ToString());
        para.Add("Password", m_UserInfo.APIPassword.ToString());
        para.Add("FactoryName", m_UserInfo.Factory);
        var strInfo = string.Empty;
        var sresult = CreateNewMfgOrder(para, ref strInfo);//dal.SaveMonthPlanData(para, ref strInfo);
        result.Result = sresult;
        result.Message = !sresult ? "保存失败：" + strInfo : "保存成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    Boolean CreateNewMfgOrder(Dictionary<string, string> para, ref string message){
        var  api = new CamstarClientAPI(para["UserName"], para["Password"]);
        var dataEntityList =new List<ClientAPIEntity>();
        var dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.RevisionedObjectField;
        dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
        dataEntity.ClientDataName = "Product";
        dataEntity.ClientDataValue = para["ProductName"];
        dataEntity.ClientDataVersion = para["ProductRevision"];
        dataEntity.ClientDataIsROR = false;
        dataEntityList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = para["Name"];
        dataEntityList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "Qty";
        dataEntity.ClientDataValue = para["Qty"];
        dataEntityList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "PlannedStartDate";
        dataEntity.ClientDataValue = para["PlannedStartDate"];
        dataEntityList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "PlannedCompletionDate";
        dataEntity.ClientDataValue = para["PlannedCompletionDate"];
        dataEntityList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
        dataEntity.ClientDataName = "Factory";
        dataEntity.ClientDataValue = para["FactoryName"];
        dataEntityList.Add(dataEntity);

        if(para.ContainsKey("OrderStatus")){
            if(!String.IsNullOrWhiteSpace(para["OrderStatus"])) {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "OrderStatus";
                dataEntity.ClientDataValue = para["OrderStatus"];
                dataEntityList.Add(dataEntity);
            }
        }
         //add by longb 20250620 订单型别
        if(para.ContainsKey("productFamily")){
           if(!String.IsNullOrWhiteSpace(para["productFamily"])) {
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "ProductFamilyName";
                dataEntity.ClientDataValue = para["productFamily"];
                dataEntityList.Add(dataEntity);
            }
        }
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
        dataEntity.ClientDataName = "OrderType";
        dataEntity.ClientDataValue = "排故订单";
        dataEntityList.Add(dataEntity);

        var ChildEntityList = new Dictionary<string, List<ClientAPIEntity>>();
        var m_Child =new  List<ClientAPIEntity>();

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = "发动机";
        m_Child.Add(dataEntity);
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "AttributeValue";
        dataEntity.ClientDataValue = para["engineNo"];
        m_Child.Add(dataEntity);
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "IsExpression";
        dataEntity.ClientDataValue = "false";
        m_Child.Add(dataEntity);
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientDataName = "DataType";
        dataEntity.ClientDataValue = "4";
        m_Child.Add(dataEntity);
        ChildEntityList.Add("0",m_Child);
        return  api.CreateModelHasSubentityList("MfgOrderMaintDoc", "MfgOrderMaint", "new", dataEntityList, "Attributes", ChildEntityList, ref message);
    }

    void SaveDealContainer(HttpContext context) 
    {
        var requestPara = JsonConvert.DeserializeObject<Dictionary<string,string>>(context.Request["data"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        var productinfo=requestPara["productinfo"];
        var strWrokflow=requestPara["strWrokflow"];
        var sql2 = @"SELECT * FROM DEALFAULTBILL d WHERE d.DEALFAULTBILLNAME ='{0}' AND d.isuse=0";
        DataTable dt2 = DatabaseHelper.Query_ReturnDatTable(string.Format(sql2, requestPara["dealFualtBill"]));
        if(dt2.Rows.Count==0){
            result.Message = "查询不到对应的排故单号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        var sql3 = @"select * from mfgorder m LEFT JOIN ORDERTYPE o2 ON o2.ORDERTYPEID =m.ORDERTYPEID where m.mfgordername='{0}' and o2.ORDERTYPENAME ='排故订单'";
        DataTable mdt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql3, requestPara["mfgOrderName"]));
        if (mdt.Rows.Count == 0)
        {
            result.Message = "查询不到对应的排故订单号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        
        var containerBaseInfo = new ContainerStartInfo();
        containerBaseInfo.ContainerName = requestPara["containerName"];//批次号
        containerBaseInfo.Qty = requestPara["qty"];//批次数量
        containerBaseInfo.MfgOrder = requestPara["mfgOrderName"];//订单号
        containerBaseInfo.MonthPlan = DateTime.Parse(requestPara["startDate"]).ToString("yyyy-MM");
        containerBaseInfo.IsSelfMfg = 1;
        containerBaseInfo.CheckTechnique = requestPara["workId"];//工艺员
        containerBaseInfo.TogetherFlag = requestPara["containerName"];//大批次号
        containerBaseInfo.Factory = m_UserInfo.Factory;//分厂
        containerBaseInfo.StartEmployee = m_UserInfo.EmployeeName;//开卡人
        containerBaseInfo.WorkCenter = requestPara["workCenterText"];//工区
        containerBaseInfo.Team = requestPara["teamText"];//班组
        containerBaseInfo.ProductName = productinfo.Substring(0, productinfo.IndexOf(":"));//件号
        containerBaseInfo.ProductRevision = productinfo.Split(':')[1].Contains("(") ? productinfo.Substring(productinfo.IndexOf(":") + 1, productinfo.LastIndexOf("(") - productinfo.IndexOf(":") - 1) : productinfo.Split(':')[1];
        containerBaseInfo.ProductuseROR = false;
        containerBaseInfo.MfgWorkflowName = strWrokflow.Substring(0, strWrokflow.IndexOf(":"));//工艺
        containerBaseInfo.MfgWorkflowRevision = strWrokflow.Substring(strWrokflow.IndexOf(":") + 1, strWrokflow.LastIndexOf("(") - strWrokflow.IndexOf(":") - 1);
        containerBaseInfo.MfgWorkflowuseROR = false;
        containerBaseInfo.WorkflowName = containerBaseInfo.MfgWorkflowName;
        containerBaseInfo.WorkflowRevision = containerBaseInfo.MfgWorkflowRevision;
        containerBaseInfo.PlannedStartDate = DateTime.Parse(requestPara["startDate"]).ToString("yyyy-MM-ddTHH:mm:ss");//开始时间
        containerBaseInfo.PlannedCompletionDate = DateTime.Parse(requestPara["endDate"]).ToString("yyyy-MM-ddTHH:mm:ss");//结束时间
        containerBaseInfo.ContainerType = requestPara["containerType"];//2：批量加工
        containerBaseInfo.QualificationQty = "1";//分开数
        var serverInfo=new ServerHostInfo();
        serverInfo.UserName = m_UserInfo.APIUserName;
        serverInfo.Password = m_UserInfo.APIPassword;
        containerBaseInfo.ServerHostInfo = serverInfo;
        FillContainerDefaultInfo(ref containerBaseInfo);//批次默认值填充
        var sql = String.Format("SELECT NVL(m.productfamilyname,'-') productfamilyname FROM mfgorder m WHERE m.mfgordername = '{0}'", containerBaseInfo.MfgOrder);
        DataTable mDT = DatabaseHelper.Query_ReturnDatTable(sql);
        if (mDT.Rows.Count == 0)
        {
            result.Message = "此订单不存在，请确认订单再进行操作";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        else {
            if (mDT.Rows[0]["productfamilyname"].ToString().Contains(","))
            {
                var pfList = new Dictionary<Int32,String>();
                var i = 1;
                foreach (var str in mDT.Rows[0]["productfamilyname"].ToString().Split(',')) 
                {
                    pfList.Add(i,str);
                    i++;
                }
                containerBaseInfo.MfgBatch = String.Format("型别：{0}|", mDT.Rows[0]["productfamilyname"].ToString().Replace(","," "));
                //containerBaseInfo.ProductFamilyList = pfList;
            }
            else {
                var pfList = new Dictionary<Int32, String>();
                pfList.Add(1, mDT.Rows[0]["productfamilyname"].ToString());
                containerBaseInfo.MfgBatch = String.Format("型别：{0} |", mDT.Rows[0]["productfamilyname"].ToString());
                //containerBaseInfo.ProductFamilyList = pfList;
            }
        }
        DataTable attributeDt = new DataTable();
        attributeDt.Columns.Add("ContainerName");
        attributeDt.Columns.Add("Level");
        attributeDt.Columns.Add("Name");
        attributeDt.Columns.Add("Value");
        DataRow newRow = attributeDt.NewRow();
        newRow["ContainerName"] = containerBaseInfo.ContainerName;
        newRow["Level"] = containerBaseInfo.Level;
        newRow["Name"] = "排故单号";
        newRow["Value"] = requestPara["dealFualtBill"];
        attributeDt.Rows.Add(newRow);
        containerBaseInfo.AttributeList = attributeDt;

        ResultStatus result2 = m_ContainerObj.StartContainer(containerBaseInfo);
        result.Result = !result2.IsError;
        result.Message =result.Result?"创建成功": "创建失败："+result2.Message.ToString().Replace("Container", "批次：").Replace("already exists", "已存在");
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void FillContainerDefaultInfo(ref ContainerStartInfo containerBaseInfo)
    {
        DataTable levelAttributes = m_CommonObj.GetFatoryAttributes(m_UserInfo.FactoryID);
        DataRow[] datarows= levelAttributes.Select("USERATTRIBUTENAME='默认所有者'");
        var strOwner="";
            if(datarows.Length > 0){ 
                strOwner = datarows[0]["ATTRIBUTEVALUE"].ToString();
            }

            datarows = levelAttributes.Select("USERATTRIBUTENAME='默认层级'");
            var strLevel = "";
            if(datarows.Length > 0){ 
                strLevel = datarows[0]["ATTRIBUTEVALUE"].ToString();
            }

            var strStart  = "";
            if(string.IsNullOrWhiteSpace(containerBaseInfo.MfgOrder.ToString())){
                datarows = levelAttributes.Select("USERATTRIBUTENAME='无订单开始原因'");
            }
            else{
                datarows = levelAttributes.Select("USERATTRIBUTENAME='订单开始原因'");
            }

            if(datarows.Length > 0){ 
                strStart = datarows[0]["ATTRIBUTEVALUE"].ToString();
            }

            containerBaseInfo.StartReason = strStart;
            containerBaseInfo.Level = strLevel;
            containerBaseInfo.Owner = strOwner;
    }
    
    
    void SaveDealMfgOrderStatus(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var strInfo = string.Empty;
        var success = false;
        foreach (DataRow row in dt.Rows)
        {
            var m_AttrList = new Dictionary<string, List<ClientAPIEntity>>();
            var dataList = new List<ClientAPIEntity>();
            var dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataName = "Name";
            dataEntity.ClientDataValue = row["MfgOrderName"];
            dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
            dataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataName = "OrderStatus";
            dataEntity.ClientDataValue = row["OrderStatus"].ToString().Equals("启用") ? "关闭" : "打开";
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
            dataList.Add(dataEntity);

            var api = new CamstarClientAPI(m_UserInfo.APIUserName.ToString(), m_UserInfo.APIPassword.ToString());
            success = api.UpdateModelHasSubentityList("MfgOrderMaintDoc", "MfgOrderMaint", row["MfgOrderName"].ToString(), "", "NDO", dataList, "Attributes", m_AttrList, 0, ref strInfo);
        }
        result.Result = success;
        result.Message = result.Result ? "操作成功" : "操作失败:" + strInfo;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

}